﻿using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

	public float speed;
	public float maxVelocity;

    public GameObject leftVision;
    public GameObject rightVision;

    public bool flip = true;
	private bool collidedObstacle;

    private bool canKicking;
    private GameObject currentLever;
    private bool leverState;
	
	public bool grounded;
    private bool lastGrounded;
	public Transform groundCheck;
	
	public CheckObstacle obstacleAhead;
	public CheckObstacle obstacleBack;
	
	public LayerMask whatIsFloor;
	public LayerMask whatIsBlock;

    public Animator fieldOfView;
    public Animator glass;
    private AnimationUtil util;
    private bool reload;

    public GameObject kickInstruction;
    public bool pause;

    public float yDead;
	IEnumerator Start () 
	{
	
        GetComponent<Animator>().enabled = false;
        glass.enabled = false;
        yield return new WaitForSeconds(0.3f);
        glass.enabled = true;
        GetComponent<Animator>().enabled = true;
        util = GetComponent<AnimationUtil>();
        GetComponent<Animator>().SetBool("TeleportComing", true);
        fieldOfView.SetBool("TeleportComing", true);    
        glass.SetBool("TeleportComing", true);
        
        StartCoroutine(util.DisableAnimationAfterTime("TeleportComing", 0.3f));
        StartCoroutine(util.DisableAnimationAfterTime("TeleportComing", 0.3f,glass));
        StartCoroutine(util.DisableAnimationAfterTime("TeleportComing", 0.3f, fieldOfView));
        
        grounded = Physics2D.OverlapCircle(groundCheck.position, 0.3f, whatIsFloor);
        lastGrounded = grounded;

	}
	
	void FixedUpdate()
	{
		grounded = Physics2D.OverlapCircle(groundCheck.position, 0.16f, whatIsFloor);

        if (lastGrounded == false && grounded && !reload)
        {
            speed = 2;
            rigidbody2D.gravityScale = 1;
            GetComponent<Animator>().SetBool("Grounded", true);
            GetComponent<AnimationController>().Glass.SetBool("Grounded", true);
            reload = true;
            StartCoroutine("Reload");
        }

		if (flip)
		{
			if (Input.GetAxisRaw ("Horizontal") > 0 && !obstacleAhead.found )
			{
				rigidbody2D.velocity = new Vector2(speed * Input.GetAxisRaw ("Horizontal"), rigidbody2D.velocity.y);
			}
			else if (Input.GetAxisRaw ("Horizontal") < 0 && !obstacleBack.found )
			{
				rigidbody2D.velocity = new Vector2(speed * Input.GetAxisRaw ("Horizontal"), rigidbody2D.velocity.y);
			}
		}
		else
		{
			if (Input.GetAxisRaw ("Horizontal") < 0 && !obstacleAhead.found )
			{
				rigidbody2D.velocity = new Vector2(speed * Input.GetAxisRaw ("Horizontal"), rigidbody2D.velocity.y);
			}
			else if (Input.GetAxisRaw ("Horizontal") > 0 && !obstacleBack.found )
			{
				rigidbody2D.velocity = new Vector2(speed * Input.GetAxisRaw ("Horizontal"), rigidbody2D.velocity.y);
			}
		}

        lastGrounded = false;
	}


	void OnCollisionStay2D(Collision2D coll)
	{
		if (coll.gameObject.tag == "Obstacle") 
		{
			collidedObstacle = true;
		}
	}
	void OnCollisionExit2D(Collision2D coll)
	{
		if (coll.gameObject.tag == "Obstacle") 
		{
			collidedObstacle = false;
		}
	}
	
	void Update () 
	{
        if (canKicking)
        {
            if (Input.GetKeyDown(KeyCode.K))
            {
                if (!leverState)
                    currentLever.SendMessage("On", SendMessageOptions.RequireReceiver);
                else
                    currentLever.SendMessage("Off", SendMessageOptions.RequireReceiver);

                leverState = !leverState;

            }

        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            Application.LoadLevel(Application.loadedLevelName);
        }

        if (transform.position.y < yDead)
        {
            Application.LoadLevel(Application.loadedLevelName);

        }

		if (collidedObstacle)
		{
			//rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
		}
        if (Input.GetKeyDown(KeyCode.Space) && !pause)
        {
           /* if (flip)
            {
                rightVision.SetActive(false);
                leftVision.SetActive(true);
            }
            else
            {
                rightVision.SetActive(true);
                leftVision.SetActive(false);
            }
			*/
            transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
            flip = !flip;
        }
	}

    void OnTriggerEnter2D (Collider2D collider)
    {
        if (collider.tag == "Platform")
        {
            transform.parent = collider.transform;
        }

        if (collider.tag == "Lever")
        {
            canKicking = true;
            if(kickInstruction)
            kickInstruction.SetActive(true);
            currentLever = collider.gameObject;
        }
        if (collider.tag == "Teleport")
        {
            this.enabled = false;
            GetComponent<Animator>().SetBool("TeleportGoing", true);
            glass.SetBool("TeleportGoing", true);
            fieldOfView.SetBool("TeleportGoing", true);
            gameObject.SendMessage("ChangeScene", SendMessageOptions.DontRequireReceiver);
        }
    }
    void OnTriggerExit2D(Collider2D collider)
    {
        if (collider.tag == "Platform")
        {
            transform.parent = null;
        }

        if (collider.tag == "Lever")
        {
            if (kickInstruction)

            kickInstruction.SetActive(false);
            canKicking = false;
            currentLever = null;
        }
    }

    IEnumerator Reload()
    {
        yield return new WaitForSeconds(.2f);
        reload = false;
    }
}
